<template>
	<view class="container pageBg">
		<view class="header">
			<view class="header-title">粉红日记 📅</view>
			<view class="header-actions">
				<view class="record-btn" @click="goToRecord">
					<text class="record-text">查看记录</text>
				</view>
			</view>
		</view>
		
		<view class="calendar-container">
			<view class="calendar-header">
				<view class="calendar-title">{{ currentYear }}年{{ currentMonth }}月</view>
				<view class="calendar-nav">
					<text @click="prevMonth">◀️</text>
					<text @click="nextMonth">▶️</text>
				</view>
			</view>
			
			<view class="calendar-grid">
				<!-- 星期头部 -->
				<view v-for="(day, index) in weekDays" :key="'week-'+index" class="weekday">{{ day }}</view>
				
				<!-- 日期格子 -->
				<view 
					v-for="(day, index) in calendarDays" 
					:key="'day-'+index" 
					class="day" 
					:class="{
						'today': day.isToday, 
						'period': day.isPeriod,
						'intimate': !day.isPeriod && day.isIntimate,
						'predicted-period': day.isPredictedPeriod,
						'predicted-ovulation': day.isPredictedOvulation,
						'other-month': !day.isCurrentMonth
					}"
					:style="{
						color: day.isCurrentMonth ? '#333' : '#ccc',
						fontStyle: day.isCurrentMonth ? 'normal' : 'italic',
						cursor: day.isCurrentMonth && mode!=='none' ? 'pointer' : 'not-allowed',
						background: day.isPeriod ? '$brand-theme-color-light' : (day.isIntimate && !day.isPeriod ? '#ffb6b6' : ''),
					}"
					@click="handleDayClick(day)"
				>
					<text class="day-number">{{ day.date }}</text>
				</view>
			</view>
		</view>
				<!-- 日期类型图例标签 -->
		<view class="calendar-legend">
			<view class="legend-item">
				<view class="day legend-day period">
					<text class="day-number">1</text>
				</view>
				<text class="legend-text">月经期</text>
			</view>
			<view class="legend-item">
				<view class="day legend-day predicted-period">
					<text class="day-number">2</text>
				</view>
				<text class="legend-text">预测经期</text>
			</view>
			<view class="legend-item">
				<view class="day legend-day predicted-ovulation">
					<text class="day-number">3</text>
				</view>
				<text class="legend-text">排卵日</text>
			</view>
			<view class="legend-item">
				<view class="day legend-day intimate">
					<text class="day-number">4</text>
				</view>
				<text class="legend-text">亲密日</text>
			</view>
		</view>
		
		<view class="quick-actions">
			<button 
				:class="['action-button', 'period-btn', {active: mode==='period'}]" 
				@mousedown="btnDown('period')" @mouseup="btnUp('period')"
				@click="toggleMode('period')"
			>
				<span>月经来了</span>
			</button>
			<button 
				:class="['action-button', 'intimate-btn', {active: mode==='intimate'}]" 
				@mousedown="btnDown('intimate')" @mouseup="btnUp('intimate')"
				@click="toggleMode('intimate')"
			>
				<span>做爱爱了</span>
			</button>
		</view>
		
		<view class="stats-container">
			<view class="stats-title">周期数据</view>					<view class="progress-container">
				<view class="ripple"></view>				
				<svg class="wd-progress" viewBox="0 0 100 100">
          <circle cx="50" cy="50" r="40" stroke="#f0f0f0" stroke-width="10" fill="none"/>
          <circle cx="50" cy="50" r="40" stroke="#FF69B4" stroke-width="10" fill="none" stroke-dasharray="251.2" stroke-dashoffset="188.4" transform="rotate(-90 50 50)"/>
        </svg>
				<view class="progress-info">
					<view class="progress-day">{{ currentCycleDay }}</view>
					<view class="progress-label">天</view>
				</view>
			</view>
			
			<view class="stats-grid">
				<view class="stat-item">
					<view class="stat-value">{{ averageCycle }}</view>
					<view class="stat-label">平均周期天数</view>
				</view>
				<view class="stat-item">
					<view class="stat-value">{{ averagePeriod }}</view>
					<view class="stat-label">平均经期天数</view>
				</view>
			</view>
			
			<view class="next-period">
				<view class="next-period-date">下次预计{{ nextPeriodDate }}</view>
				<view class="next-period-days">还有 {{ daysUntilNextPeriod }} 天</view>
			</view>
		</view>
		
		<wd-toast ref="toast" />
		
		<!-- 亲密记录设置弹窗 -->
		<uni-popup ref="intimatePopup" type="center">
			<view class="intimate-popup">
				<view class="intimate-popup-title">亲密记录</view>
				
				<!-- 保护措施选择 -->
				<view class="intimate-section">
					<view class="intimate-section-title">是否有保护措施？</view>
					<view class="protection-options">
						<view 
							class="protection-option" 
							:class="{ active: hasProtection }" 
							@click="hasProtection = true"
						>
							<text>有</text>
						</view>
						<view 
							class="protection-option" 
							:class="{ active: !hasProtection }" 
							@click="hasProtection = false"
						>
							<text>无</text>
						</view>
					</view>
				</view>
				
				<!-- 情绪评分 -->
				<view class="intimate-section">
					<view class="intimate-section-title">情绪评分</view>
					<view class="mood-slider">
						<slider 
							:value="intimateMood" 
							min="1" 
							max="5" 
							step="1" 
							show-value 
							@change="onMoodChange"
							activeColor="#FF6B6B"
						></slider>
						<view class="mood-labels">
							<text>很糟</text>
							<text>一般</text>
							<text>很好</text>
						</view>
					</view>
				</view>
				
				<!-- 弹窗按钮 -->
				<view class="intimate-btns">
					<button class="intimate-btn cancel-btn" @click="closeIntimatePopup">取消</button>
					<button class="intimate-btn confirm-btn" @click="confirmIntimateRecord">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { onShareAppMessage } from '@dcloudio/uni-app'

// 云开发相关配置
const spaceId = 'mp-f9881352-2084-4a8f-b3ef-b52bdf18452c'
const clientSecret = '7ubwCOOf8ZdSFMOUL2pd1A=='

// 星期头部
const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 当前日期相关
const today = new Date()
const currentDate = ref(new Date())
const currentYear = computed(() => currentDate.value.getFullYear())
const currentMonth = computed(() => currentDate.value.getMonth() + 1)

// 经期和亲密日期记录
const periodDates = ref([])
const intimateDates = ref([])
const userId = ref('') // 用户ID，从登录信息获取

// 亲密记录设置弹窗相关
const intimatePopup = ref(null)
const intimateRecord = ref(null)
const hasProtection = ref(false)
const intimateMood = ref(3)

// 提醒功能相关
async function checkPeriodReminder() {
	try {
		// 检查用户是否订阅了提醒消息
		const hasSubscribedMessage = uni.getStorageSync('hasSubscribedMessage')
		if (hasSubscribedMessage !== 'true') {
			console.log('用户未订阅提醒消息，跳过提醒检查')
			return
		}
		
		// 从本地存储获取上次发送提醒的时间戳
		const lastReminderSent = uni.getStorageSync('lastReminderSent')
		
		// 获取今天零点的时间戳
		const today = new Date()
		today.setHours(0, 0, 0, 0)
		const todayTimestamp = today.getTime()
		
		// 如果今天已经发送过提醒，则不再发送
		if (lastReminderSent && parseInt(lastReminderSent) >= todayTimestamp) {
			console.log('今天已经发送过提醒，跳过发送')
			return
		}
		
		// 获取预测的经期开始日期
		const predictedPeriods = getPredictedPeriods()
		if (predictedPeriods.length === 0) {
			console.log('没有预测的经期数据，跳过提醒')
			return
		}
		
		// 如果提醒天数是1、2或3天，发送微信订阅消息
		if (daysUntilNextPeriod.value <= 3 && daysUntilNextPeriod.value > 0) {
			console.log(`距离下次经期还有${daysUntilNextPeriod.value}天，符合提醒条件`)
			
			// 获取用户openid
			let openid = uni.getStorageSync('openid')
			
			// 如果没有openid，尝试获取
			if (!openid) {
				console.log('本地未保存openid，尝试获取')
				openid = await getOpenid()
			}
			
			if (!openid) {
				console.log('无法获取openid，无法发送提醒')
				return
			}
			
			// 获取用户基本信息
			const userInfo = uni.getStorageSync('userInfo')
			let nickName = '亲爱的用户'
			if (userInfo) {
				try {
					const parsedInfo = JSON.parse(userInfo)
					nickName = parsedInfo.nickName || '亲爱的用户'
				} catch (e) {
					console.error('解析用户信息失败:', e)
				}
			}
			
			console.log('准备发送经期提醒...')
			
			// 发送微信订阅消息
			const success = await sendPeriodReminder(nickName, daysUntilNextPeriod.value)
			
			if (success) {
				// 记录今天已发送提醒
				uni.setStorageSync('lastReminderSent', todayTimestamp)
				console.log('经期提醒发送成功，已记录发送状态')
			}
		} else {
			console.log(`距离下次经期还有${daysUntilNextPeriod.value}天，不符合提醒条件(需<=3天)`)
		}
	} catch (error) {
		console.error('经期提醒检查失败:', error)
	}
}

// 获取用户openid
async function getOpenid() {
	try {
		console.log('正在获取用户openid...')
		
		// 初始化云环境
		await initCloud()
		
		// 调用获取openid的云函数
		const result = await uniCloud.callFunction({
			name: 'getOpenid',
			data: {
				userId: userId.value || 'home_user',
				isTestEnv: true // 标记为测试环境
			}
		})
		
		if (result.result && result.result.code === 0 && result.result.openid) {
			const openid = result.result.openid
			console.log('获取到openid:', openid)
			uni.setStorageSync('openid', openid)
			return openid
		} else {
			console.error('获取openid失败:', result.result)
			return ''
		}
	} catch (error) {
		console.error('获取openid错误:', error)
		return ''
	}
}

// 发送经期提醒消息
async function sendPeriodReminder(name, days) {
	// 获取用户openid
	const openid = uni.getStorageSync('openid') || ''
	if (!openid) {
		console.log('未获取到openid，无法发送微信提醒')
		return false
	}
	
	// 获取预测的下次经期开始日期
	const nextPeriodStartDate = getPredictedPeriods()[0]
	
	// 构建提醒消息参数
	const message = {
		userId: userId.value,
		type: 'period_reminder',
		title: '月经提醒',
		content: `${name}，温馨提醒：您的下次月经预计将在${days}天后开始（${nextPeriodDate.value}）。请做好相关准备哦！`,
		createdAt: new Date().toISOString(),
		periodDuration: averagePeriod.value, // 添加平均经期持续天数
		openid: openid // 添加openid用于发送微信订阅消息
	}
	
	try {
		// 初始化云环境
		await initCloud()
		
		console.log('调用sendUserNotification云函数，参数:', JSON.stringify(message))
		
		// 调用云函数发送提醒
		const result = await uniCloud.callFunction({
			name: 'sendUserNotification',
			data: message
		})
		
		console.log('sendUserNotification返回结果:', result)
		
		if (result.result && result.result.code === 0) {
			console.log('经期提醒发送成功')
			return true
		} else {
			const errorMsg = result.result ? result.result.message : '未知错误'
			console.error('发送提醒失败:', errorMsg)
			return false
		}
	} catch (error) {
		console.error('发送经期提醒消息失败:', error)
		return false
	}
}

// 日历数据
const calendarDays = ref([])

// 生成日历数据
const generateCalendarDays = () => {
	const year = currentDate.value.getFullYear()
	const month = currentDate.value.getMonth()
	
	// 获取当月第一天是星期几
	const firstDay = new Date(year, month, 1).getDay()
	
	// 获取当月天数
	const daysInMonth = new Date(year, month + 1, 0).getDate()
	
	// 获取上月天数
	const daysInPrevMonth = new Date(year, month, 0).getDate()
	
	// 清空日历数据
	calendarDays.value = []
	
	// 添加上月天数
	for (let i = firstDay - 1; i >= 0; i--) {
		const date = daysInPrevMonth - i
		const dateObj = new Date(year, month - 1, date)
		const isPeriod = isPeriodDay(dateObj)
		const isIntimate = isIntimateDay(dateObj)
		calendarDays.value.push({
			date,
			timestamp: dateObj.getTime(),
			isToday: isSameDay(dateObj, today),
			isPeriod,
			isIntimate,
			isPredictedPeriod: !isPeriod && !isIntimate && isPredictedPeriodDay(dateObj),
			isPredictedOvulation: !isPeriod && !isIntimate && isPredictedOvulationDay(dateObj),
			isCurrentMonth: false
		})
	}
	
	// 添加当月天数
	for (let date = 1; date <= daysInMonth; date++) {
		const dateObj = new Date(year, month, date)
		const isPeriod = isPeriodDay(dateObj)
		const isIntimate = isIntimateDay(dateObj)
		calendarDays.value.push({
			date,
			timestamp: dateObj.getTime(),
			isToday: isSameDay(dateObj, today),
			isPeriod,
			isIntimate,
			isPredictedPeriod: !isPeriod && !isIntimate && isPredictedPeriodDay(dateObj),
			isPredictedOvulation: !isPeriod && !isIntimate && isPredictedOvulationDay(dateObj),
			isCurrentMonth: true
		})
	}
	
	// 计算还需要添加多少下月的天数
	const nextMonthDays = 42 - calendarDays.value.length
	
	// 添加下月天数
	for (let date = 1; date <= nextMonthDays; date++) {
		const dateObj = new Date(year, month + 1, date)
		const isPeriod = isPeriodDay(dateObj)
		const isIntimate = isIntimateDay(dateObj)
		calendarDays.value.push({
			date,
			timestamp: dateObj.getTime(),
			isToday: isSameDay(dateObj, today),
			isPeriod,
			isIntimate,
			isPredictedPeriod: !isPeriod && !isIntimate && isPredictedPeriodDay(dateObj),
			isPredictedOvulation: !isPeriod && !isIntimate && isPredictedOvulationDay(dateObj),
			isCurrentMonth: false
		})
	}
}

// 判断是否是同一天
const isSameDay = (date1, date2) => {
	return date1.getFullYear() === date2.getFullYear() &&
		   date1.getMonth() === date2.getMonth() &&
		   date1.getDate() === date2.getDate()
}

// 判断是否是经期
const isPeriodDay = (date) => {
	return periodDates.value.some(period => isSameDay(new Date(period), date))
}

// 判断是否是亲密日
const isIntimateDay = (date) => {
	return !isPeriodDay(date) && intimateDates.value.some(intimate => isSameDay(new Date(intimate), date))
}

// 判断是否是预测经期
function isPredictedPeriodDay(date) {
	// 只预测未来日期
	if (date.getTime() <= today.getTime()) return false
	
	const predicted = getPredictedPeriods()
	for(const d of predicted) {
		// 预测经期持续5天
		for(let i = 0; i < getAvgPeriodDays(); i++) {
			const pd = new Date(d.getFullYear(), d.getMonth(), d.getDate() + i)
			if(isSameDay(pd, date)) {
				return true
			}
		}
	}
	return false
}

// 排卵预测
function getPredictedOvulations() {
	const predicted = getPredictedPeriods() // 获取预测的下次经期
	if(predicted.length < 1) return []
	
	// 获取平均周期
	const avgCycle = getAvgCycle()
	// 下次经期
	const nextPeriod = predicted[0]
	
	// 排卵日通常在下次经期前14天
	const nextOvulation = new Date(nextPeriod.getTime() - 14 * 24 * 3600 * 1000)
	return [nextOvulation]
}

function isPredictedOvulationDay(date) {
	// 只预测未来日期
	if (date.getTime() <= today.getTime()) return false
	
	const ovulations = getPredictedOvulations()
	for(const d of ovulations) {
		// 排卵日前后2天
		for(let i = -2; i <= 2; i++) {
			const od = new Date(d.getFullYear(), d.getMonth(), d.getDate() + i)
			if(isSameDay(od, date)) {
				return true
			}
		}
	}
	return false
}

// 切换月份
const prevMonth = () => {
	currentDate.value = new Date(currentYear.value, currentMonth.value - 2, 1)
	generateCalendarDays()
}

const nextMonth = () => {
	currentDate.value = new Date(currentYear.value, currentMonth.value, 1)
	generateCalendarDays()
}

// 周期统计数据
const averageCycle = ref(28)
const averagePeriod = ref(5)
const currentCycleDay = ref(1)
const nextPeriodDate = ref('')
const daysUntilNextPeriod = ref(0)

// 计算统计数据
const calculateStats = () => {
	// 计算平均周期天数
	averageCycle.value = getAvgCycle()
	
	// 计算平均经期天数
	averagePeriod.value = getAvgPeriodDays()
	
	// 计算当前周期天数
	const recentPeriods = getRecentPeriods()
	if (recentPeriods.length > 0) {
		const latestPeriod = recentPeriods[0]
		const daysSinceLastPeriod = Math.floor((today.getTime() - latestPeriod.getTime()) / (24 * 60 * 60 * 1000))
		currentCycleDay.value = daysSinceLastPeriod + 1
	} else {
		currentCycleDay.value = 1
	}
	
	// 计算下次经期日期
	const predictedPeriods = getPredictedPeriods()
	if (predictedPeriods.length > 0) {
		const nextPeriod = predictedPeriods[0]
		const month = nextPeriod.getMonth() + 1
		const day = nextPeriod.getDate()
		nextPeriodDate.value = `${month}月${day}日`
		
		// 计算距离下次经期的天数
		const diffTime = nextPeriod.getTime() - today.getTime()
		daysUntilNextPeriod.value = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
		
		// 检查是否需要发送经期提醒
		checkPeriodReminder()
	} else {
		nextPeriodDate.value = '暂无预测'
		daysUntilNextPeriod.value = 0
	}
}

const mode = ref('none') // 'none' | 'period' | 'intimate'

function toggleMode(type) {
	mode.value = mode.value === type ? 'none' : type
}

function btnDown(type) {
	const btn = document.querySelector(type==='period'?'.period-btn':'.intimate-btn')
	if(btn) btn.style.transform = 'scale(0.95)'
}
function btnUp(type) {
	const btn = document.querySelector(type==='period'?'.period-btn':'.intimate-btn')
	if(btn) btn.style.transform = 'scale(1)'
}

// 处理日期点击事件
async function handleDayClick(day) {
	if (!day.isCurrentMonth || mode.value === 'none') return
	
	if (!userId.value) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		return
	}
	
	try {
		await initCloud()
		
		// 修复日期时区问题，确保使用本地日期而不是UTC日期
		const clickDate = new Date(day.timestamp)
		// 创建一个基于本地时区的日期字符串 YYYY-MM-DD
		const dateString = `${clickDate.getFullYear()}-${String(clickDate.getMonth() + 1).padStart(2, '0')}-${String(clickDate.getDate()).padStart(2, '0')}`
		
		if (mode.value === 'period') {
			const isMarked = periodDates.value.some(ts => isSameDay(new Date(ts), new Date(day.timestamp)))
			
			if (isMarked) {
				// 取消标记
				await uniCloud.callFunction({
					name: 'deletePeriodRecord',
					data: {
						userId: userId.value,
						date: dateString
					}
				})
				
				// 移除本地记录
				const idx = periodDates.value.findIndex(ts => isSameDay(new Date(ts), new Date(day.timestamp)))
				if (idx > -1) periodDates.value.splice(idx, 1)
				
				uni.showToast({
					title: '已取消标记',
					icon: 'none'
				})
			} else {
				// 添加标记
				await uniCloud.callFunction({
					name: 'addPeriodRecord',
					data: {
						userId: userId.value,
						date: dateString
					}
				})
				
				// 添加到本地记录
				periodDates.value.push(day.timestamp)
				
				uni.showToast({
					title: '已标记为经期',
					icon: 'none'
				})
			}
			
			// 重新生成日历数据
			generateCalendarDays()
			
			// 更新统计数据
			calculateStats()
		} else if (mode.value === 'intimate') {
			const isMarked = intimateDates.value.some(ts => isSameDay(new Date(ts), new Date(day.timestamp)))
			
			if (isMarked) {
				// 取消标记
				await uniCloud.callFunction({
					name: 'deleteIntimateRecord',
					data: {
						userId: userId.value,
						date: dateString
					}
				})
				
				// 移除本地记录
				const idx = intimateDates.value.findIndex(ts => isSameDay(new Date(ts), new Date(day.timestamp)))
				if (idx > -1) intimateDates.value.splice(idx, 1)
				
				uni.showToast({
					title: '已取消标记',
					icon: 'none'
				})
				
				// 重新生成日历数据
				generateCalendarDays()
				
				// 更新统计数据
				calculateStats()
			} else {
				// 显示亲密记录设置弹窗
				intimateRecord.value = {
					dateString,
					timestamp: day.timestamp
				}
				intimatePopup.value.open()
			}
		}
	} catch (error) {
		console.error('处理日期点击失败:', error)
		uni.showToast({
			title: '操作失败，请重试',
			icon: 'none'
		})
	}
}

// 月经预测（粉色虚线圆圈）
function getRecentPeriods() {
	// 取最近6次，按时间排序
	const arr = periodDates.value
		.map(ts => new Date(ts))
		.sort((a, b) => b.getTime() - a.getTime()) // 降序排序，最新的在前面
	return arr.slice(0, 6)
}

function getAvgCycle() {
	const arr = getRecentPeriods()
	if(arr.length < 2) return 28
	
	// 找到经期开始日期（每组经期的第一天）
	const periodStarts = []
	for(let i = 0; i < arr.length; i++) {
		const current = arr[i]
		// 检查这个日期是否是这组经期的第一天
		const isStart = !arr.some(d => 
			d.getFullYear() === current.getFullYear() &&
			d.getMonth() === current.getMonth() &&
			d.getDate() === current.getDate() - 1
		)
		if(isStart) {
			periodStarts.push(current)
		}
	}
	
	// 计算平均周期
	if(periodStarts.length < 2) return 28
	let sum = 0, count = 0
	for(let i = 1; i < periodStarts.length; i++) {
		const diff = Math.abs(periodStarts[i-1].getTime() - periodStarts[i].getTime())
		const days = Math.round(diff / (1000 * 3600 * 24))
		if(days > 0) {
			sum += days
			count++
		}
	}
	return Math.round(sum/count) || 28
}

function getAvgPeriodDays() {
	// 先将所有经期日期升序排列
	const arr = periodDates.value
		.map(ts => new Date(ts))
		.sort((a, b) => a.getTime() - b.getTime())

	if(arr.length < 1) return 5

	// 按连续性分组，每组为一次完整经期
	const periodGroups = []
	let currentGroup = []

	for(let i = 0; i < arr.length; i++) {
		if(currentGroup.length === 0) {
			currentGroup.push(arr[i])
		} else {
			const prevDate = arr[i-1]
			const currDate = arr[i]
			const diffDays = Math.round((currDate.getTime() - prevDate.getTime()) / (1000 * 3600 * 24))
			if(diffDays === 1) {
				currentGroup.push(currDate)
			} else {
				periodGroups.push([...currentGroup])
				currentGroup = [currDate]
			}
		}
	}
	if(currentGroup.length > 0) {
		periodGroups.push(currentGroup)
	}

	// 只取最近3~6组（如有多于6组）
	const recentGroups = periodGroups.slice(-6)
	const totalDays = recentGroups.reduce((sum, group) => sum + group.length, 0)
	const periodCount = recentGroups.length

	return periodCount > 0 ? Math.round(totalDays / periodCount) : 5
}

function getPredictedPeriods() {
	const arr = getRecentPeriods()
	if(arr.length < 1) return []
	const avgCycle = getAvgCycle()
	const lastPeriod = arr[0] // 使用最近的一次经期
	const nextStart = new Date(lastPeriod.getTime() + avgCycle * 24 * 3600 * 1000)
	return [nextStart]
}

onShareAppMessage(() => {
	return {
		title: '粉红日记',
		path: '/pages/home/home'
	}
})

const goToRecord = () => {
	uni.navigateTo({
		url: '/pages/record/record'
	})
}

// 关闭亲密记录弹窗
function closeIntimatePopup() {
	intimatePopup.value.close()
}

// 情绪评分变化
function onMoodChange(e) {
	intimateMood.value = e.detail.value
}

// 确认添加亲密记录
async function confirmIntimateRecord() {
	if (!intimateRecord.value || !userId.value) {
		uni.showToast({
			title: '数据错误，请重试',
			icon: 'none'
		})
		return
	}
	
	try {
		// 添加标记
		await uniCloud.callFunction({
			name: 'addIntimateRecord',
			data: {
				userId: userId.value,
				date: intimateRecord.value.dateString,
				hasProtection: hasProtection.value,
				mood: intimateMood.value
			}
		})
		
		// 添加到本地记录
		intimateDates.value.push(intimateRecord.value.timestamp)
		
		uni.showToast({
			title: '已标记为亲密日',
			icon: 'success'
		})
		
		// 重新生成日历数据
		generateCalendarDays()
		
		// 更新统计数据
		calculateStats()
		
		// 重置并关闭弹窗
		hasProtection.value = false
		intimateMood.value = 3
		closeIntimatePopup()
	} catch (error) {
		console.error('添加亲密记录失败:', error)
		uni.showToast({
			title: '添加失败，请重试',
			icon: 'none'
		})
	}
}

// 初始化云开发
const initCloud = () => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '加载中'
		})
		
		uniCloud.init({
			spaceId,
			clientSecret,
			provider: 'aliyun'
		})
		
		uni.hideLoading()
		resolve()
	})
}

// 页面加载时检查登录状态
onMounted(() => {
	// 检查登录状态
	checkLoginStatus()
})

// 检查登录状态
const checkLoginStatus = () => {
	const isLogin = uni.getStorageSync('isLogin')
	if (isLogin !== 'true') {
		console.log('用户未登录，跳转到登录页')
		uni.navigateTo({
			url: '/pages/login/login'
		})
		return false
	}
	
	// 获取用户ID
	const userInfo = uni.getStorageSync('userInfo')
	if (userInfo) {
		try {
			const parsedInfo = JSON.parse(userInfo)
			userId.value = parsedInfo.userId || parsedInfo._id || ''
		} catch (e) {
			console.error('解析用户信息失败:', e)
		}
	}
	
	// 加载用户数据
	loadUserData()
	
	return true
}

// 加载用户数据
const loadUserData = async () => {
	if (!userId.value) {
		console.error('用户ID不存在，无法加载数据')
		return
	}
	
	try {
		await initCloud()
		
		// 加载经期记录
		const periodResult = await uniCloud.callFunction({
			name: 'getPeriodRecords',
			data: {
				userId: userId.value
			}
		})
		
		if (periodResult.result && periodResult.result.code === 0) {
			// 将云端数据转换为本地格式
			periodDates.value = periodResult.result.data.map(item => new Date(item.date).getTime())
		}
		
		// 加载亲密日记录
		const intimateResult = await uniCloud.callFunction({
			name: 'getIntimateRecords',
			data: {
				userId: userId.value
			}
		})
		
		if (intimateResult.result && intimateResult.result.code === 0) {
			// 将云端数据转换为本地格式
			intimateDates.value = intimateResult.result.data.map(item => new Date(item.date).getTime())
		}
		
		// 初始化日历数据
		generateCalendarDays()
		
		// 计算统计数据
		calculateStats()
		
		// 检查是否需要发送经期提醒
		checkPeriodReminder()
		
	} catch (error) {
		console.error('加载用户数据失败:', error)
		uni.showToast({
			title: '加载数据失败，请重试',
			icon: 'none'
		})
	}
}
</script>

<style lang="scss" scoped>
.container {
	padding: 20px 16px;
	max-width: 375px;
	margin: 0 auto;
	background-color: $background-color;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.header-title {
	font-size: 24px;
	font-weight: bold;
	color: $brand-theme-color;
	margin-left: 12px;
}

.header-actions {
	display: flex;
	align-items: center;
	gap: 12px;
}

.record-btn {
	background-color: $brand-theme-color;
	color: white;
	padding: 6px 12px;
	border-radius: 16px;
	font-size: 14px;
	cursor: pointer;
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.95);
	}
}

.record-text {
	font-weight: 500;
}

.calendar-container {
	background-color: $white;
	border-radius: 12px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	padding: 16px;
	margin-bottom: 20px;
}

.calendar-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.calendar-title {
	font-size: 18px;
	font-weight: bold;
	color: $brand-theme-color;
}

.calendar-nav {
	display: flex;
	gap: 16px;
}

.calendar-grid {
	display: grid;
	grid-template-columns: repeat(7, 1fr);
	gap: 4px;
	width: 100%;
}

.weekday {
	text-align: center;
	font-size: 12px;
	color: #666;
	padding: 8px 0;
	width: 100%;
}

.day {
	position: relative;
	width: 100%;
	aspect-ratio: 1;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 50%;
	font-size: 14px;
	margin: 0 auto;
	cursor: pointer;
	transition: background 0.3s, color 0.3s;
	max-width: 40px;
}

.day-number {
	z-index: 2;
}

.today {
	font-weight: bold;
	border: 2px solid $brand-theme-color;
}

.period {
	background-color: $brand-theme-color !important;
	color: white !important;
}

.period::after {
	content: "💧";
	position: absolute;
	font-size: 12px;
	bottom: 0;
      right: 0;
}

.predicted-period {
	border: 2px dashed $brand-theme-color !important;
	background: none !important;
}

.predicted-period::after {
	content: "📅";
	position: absolute;
	font-size: 12px;
	bottom: -2px;
	right: -2px;
}

.intimate {
	position: relative;
	background-color:  #FF6B6B !important;
	color: white !important;
}

.intimate::after {
	content: "❤️";
	position: absolute;
	font-size: 12px;
	top: 0;
	right: 0;
}

.predicted-ovulation {
	position: relative;
	border: 2px dashed orange !important;
	background: none !important;
}

.predicted-ovulation::after {
	content: "🥚";
	position: absolute;
	font-size: 12px;
	bottom: 0;
	right: 0;
}

.other-month {
	color: #ccc !important;
	font-style: italic;
}

.quick-actions {
	display: flex;
	justify-content: space-between;
	gap: 16px;  
	margin-bottom: 20px; 
	position: sticky;
	bottom: 20px;
	z-index: 10;
}

.action-button {
	flex: 1;
	border: 1px solid $brand-theme-color;
	border-radius: 24px;
	font-size: 14px;
	font-weight: bold;
	margin: 0 8px;
	padding: 12px 16px;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #fff;
	color:$brand-theme-color;
	transition: background 0.3s, color 0.3s, border 0.3s, transform 0.2s;
	box-shadow: 0 4px 8px rgba(255, 105, 180, 0.3);
	cursor: pointer;
}

.quick-actions .action-button.active,
.quick-actions .action-button.active:focus,
.quick-actions .action-button.active:visited {
	background: $brand-theme-color !important;
	color: #fff !important;
	border: 2px solid $brand-theme-color !important;
	box-shadow: 0 2px 8px $brand-theme-color-light;
}

.action-button:active {
	transform: scale(0.95);
}

.stats-container {
	background-color: white;
	border-radius: 12px;
	padding: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stats-title {
	font-size: 16px;
	font-weight: bold;
	color: $brand-theme-color;
	margin-bottom: 16px;
}

.progress-container {
	position: relative;
	width: 100px;
	height: 100px;
	margin: 0 auto 16px;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #fff;
}

.ripple {
	position: absolute;
	width: 100%;
	height: 100%;
	background-color: #FFE4E7;
	border-radius: 50%;
	opacity: 0.3;
	animation: rippleEffect 1.5s infinite ease-out;
}

@keyframes rippleEffect {
	0% {
        transform: scale(0.8);
        opacity: 1;
      }
      100% {
        transform: scale(1.2);
        opacity: 0;
      }
}

.progress-info {
	 position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
}

.progress-day {
	font-size: 24px;
	font-weight: bold;
	color: #FF4D6A;
	line-height: 1;
	margin-bottom: 4px;
}

.progress-label {
	font-size: 12px;
	color: #FF4D6A;
	opacity: 0.8;
}

.stats-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 16px;
}

.stat-item {
	text-align: center;
}

.stat-value {
	font-size: 18px;
	font-weight: bold;
	color: $brand-theme-color;
}

.stat-label {
	font-size: 12px;
	color: #666;
}

.next-period {
	background-color: $brand-theme-color-light;
	color: white;
	border-radius: 8px;
	padding: 12px;
	text-align: center;
	margin-top: 16px;
}

.next-period-date {
	font-size: 18px;
	font-weight: bold;
}

.next-period-days {
	font-size: 14px;
}



/* 日期类型图例标签 */
.calendar-legend {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background-color: $white;
	border-radius: 12px;
	padding: 12px 16px;
	margin: -10px 0 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.legend-item {
	display: flex;
	align-items: center;
	gap: 8px;
}

.legend-day {
	width: 28px !important;
	height: 28px !important;
	font-size: 12px !important;
}

.legend-text {
	font-size: 11.5px;
	color: #666;
	font-weight: 500;
}

.wd-progress {
	width: 100px;
	height: 100px;
}

/* 亲密记录弹窗样式 */
.intimate-popup {
	background-color: white;
	border-radius: 16px;
	width: 300px;
	padding: 20px;
	box-sizing: border-box;
}

.intimate-popup-title {
	font-size: 18px;
	font-weight: bold;
	color: $brand-theme-color;
	text-align: center;
	margin-bottom: 16px;
}

.intimate-section {
	margin-bottom: 16px;
}

.intimate-section-title {
	font-size: 16px;
	color: #333;
	margin-bottom: 12px;
}

.protection-options {
	display: flex;
	justify-content: space-between;
}

.protection-option {
	flex: 1;
	text-align: center;
	padding: 10px 0;
	margin: 0 8px;
	border-radius: 20px;
	background-color: #f5f5f5;
	color: #333;
	font-size: 16px;
	transition: all 0.3s;
}

.protection-option.active {
	background-color: $brand-theme-color;
	color: white;
}

.mood-slider {
	padding: 0 8px;
	margin-top: 8px;
}

.mood-labels {
	display: flex;
	justify-content: space-between;
	font-size: 12px;
	color: #666;
	margin-top: 4px;
}

.intimate-btns {
	display: flex;
	justify-content: space-between;
	margin-top: 20px;
}

.intimate-btn {
	flex: 1;
	margin: 0 8px;
	padding: 10px 0;
	border-radius: 20px;
	font-size: 16px;
	border: none;
}

.cancel-btn {
	background-color: #f5f5f5;
	color: #333;
}

.confirm-btn {
	background-color: $brand-theme-color;
	color: white;
}
</style>
